/*
 *  ufmail, a suite of mail servers
 *  Copyright (C) 2013  Jonathon Keogh
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 * 
 *  Jonathon Keogh e-mail: jdkeogh@live.com
 */

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <errno.h>
#include <pthread.h>
#include "ufmail.h"
#include "log.h"
#include "thread.h"
#include "server-smtp-thread.h"
#include "server-smtp-init.h"

void *initServer_SMTP(void *vNull) {
	int i, i2, i3, i4, *i5, *iSocket = &iServerSocket[SOCK_SMTP];
	struct sockaddr_in stServer, stClient;

	// Child
	// Allocate threads
	stSMTPThreads = initThreads(CONFIG_THREADSPERSERVER);
	if(stSMTPThreads == NULL) {
		// Error
		writeToLog(LOG_ERROR, "(SMTP) Unable to start server, could not init threads", strerror(errno));
		return;
	}

	// Create an endpoint for communication
	*iSocket = socket(AF_INET, SOCK_STREAM, 0);
	if(*iSocket < 0) {
		// Error
		writeToLog(LOG_ERROR, "(SMTP) Unable to start server, socket() did not succeed, %s", strerror(errno));
		return;
	}
		
	// Initialise server socket info structure
	memset(&stServer, 0, sizeof(struct sockaddr_in));
	stServer.sin_family = AF_INET;
	stServer.sin_addr.s_addr = htonl(INADDR_ANY);
	stServer.sin_port = htons(CONFIG_PORT_SMTP);

	// Bind a name to a socket
	if(bind(*iSocket, (struct sockaddr *) &stServer, sizeof(struct sockaddr_in)) != 0) {
		// Error
		writeToLog(LOG_ERROR, "(SMTP) Unable to start server, bind() did not succeed, %s", strerror(errno));
		return;
	}
		
	// Listen for connections on the socket
	if(listen(*iSocket, CONFIG_BACKLOG) != 0) {
		// Error
		writeToLog(LOG_ERROR, "(SMTP) Unable to start server, listen() did not succeed, %s", strerror(errno));
		return;
	}
		
	// Info
	writeToLog(LOG_INFO, "(SMTP) Waiting for connections.");
		
	// Loop
	while(1) {
		// Init i
		i = sizeof(sizeof(struct sockaddr_in));
		
		// Accept a connection (i2 is the client)
		i2 = accept(*iSocket, (struct sockaddr *) &stClient, &i);
		if(i2 < 0) {
			// TODO If this repeats then consider exiting after, say, 5 failures for same errno within the space of 1 minute?
			// Error
			writeToLog(LOG_ERROR, "(SMTP) Unable to start server, accept() did not succeed, %s", strerror(errno));
			continue;
		}

		// Record who has connected
		writeToLog(LOG_INFO, "(SMTP) Client connected %s", inet_ntoa(stClient.sin_addr));
		
		// TODO Retry a couple of times? Instead of just disconnecting if not available
		// Look for the next thread to allocate
		i4 = -1;
		for(i3=0;i3<CONFIG_THREADSPERSERVER;i3++) {
			if(stSMTPThreads[i3]->shInUse == 0) {
				i4 = i3;
				break;
			}
		}
		if(i4 == -1) {
			// TODO Send busy error?
			writeToLog(LOG_INFO, "(SMTP) Connection closed - no threads available");
			close(i2);
			continue;
		}

		// Connection accepted - pass to thread
		i5 = malloc(sizeof(int)); // Responsibility of the thread to free this
		*i5 = i4;
		stSMTPThreads[i4]->shInUse = 1;
		stSMTPThreads[i4]->iClient = i2;
		stSMTPThreads[i4]->sDataQueue = malloc(1); // Init data queue
		stSMTPThreads[i4]->sDataQueue[0] = 0;
		stSMTPThreads[i4]->sProcessNow = malloc(1); // Init process now
		stSMTPThreads[i4]->sProcessNow[0] = 0;
		pthread_mutex_lock(&stSMTPThreads[i4]->mutex_sProcessNow); // The Recv thread automatically has the lock
		pthread_create(&stSMTPThreads[i4]->pThreadRecv, NULL, threadRecv_SMTP, (void *) i5);
		pthread_create(&stSMTPThreads[i4]->pThreadServer, NULL, threadServer_SMTP, (void *) i5);
	}
}
